package cn.doctorpda.conference.presenter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;

import cn.doctorpda.conference.bean.DataReportInfo;
import cn.doctorpda.conference.bean.Msg;
import cn.doctorpda.conference.bean.ReportInfoItem;
import cn.doctorpda.conference.config.AppConfig;
import cn.doctorpda.conference.config.NetConfig;
import cn.doctorpda.conference.model.GetReportModel;
import cn.doctorpda.conference.model.IPostModel;
import cn.doctorpda.conference.okhttp.callback.StringCallback;
import cn.doctorpda.conference.utils.AESUtil;
import cn.doctorpda.conference.utils.GsonUtil;
import cn.doctorpda.conference.utils.L;
import cn.doctorpda.conference.view.callbackview.IReportPageView;
import okhttp3.Call;

/**
 * Created by huangjinlong on 2016/5/24.
 */
public class ReportPresenter {
    private IReportPageView baseView;
    private IPostModel model;
    private DataReportInfo info = new DataReportInfo();

    public ReportPresenter(IReportPageView baseView) {
        this.baseView = baseView;
        model = new GetReportModel();
    }

    public void getReport(final String page, String limit, String type, String keyword) {
        model.postNetWorkStringData(NetConfig.GET_REPORT_LIST, new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {
                baseView.setReportError(call, e);
            }

            @Override
            public void onResponse(String response) {

                try {
                    Msg msg = GsonUtil.fromJson(response, Msg.class);
                    JSONObject jsonObject = new JSONObject(response);

                    if (jsonObject.getInt("code") == 0) {
                        String data = AESUtil.decrypt(msg.getData(), AppConfig.AES_KEY);
                        L.i("报道" + data);
                        Type listType = new TypeToken<ArrayList<ReportInfoItem>>() {
                        }.getType();
                        Gson gson = new Gson();
                        ArrayList<ReportInfoItem> resources = gson.fromJson(data, listType);
                        info.setList(resources);
                    } else {

                    }
                    if (page.equals("1")) {
                        baseView.setRReportResult(msg, info);
                    } else {
                        baseView.setLReportResult(msg, info);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, page, limit, type, keyword);
    }
}
